<template>
  <div style="display: flex;justify-content: space-around">
    <div>
      <div style="border: #cccccc 1px solid;width: 400px">
        <vue-esign
            ref="esign"
            :width="400"
            :height="400"
            :isCrop="isCrop"
            :lineWidth="lineWidth"
            :lineColor="lineColor"
        />
      </div>
      <button @click="handleReset">清空画板</button>
      <button @click="handleGenerate">生成图片</button>
    </div>
    <div>
      <img style="border: #cccccc 1px solid;" :src="imgSrc" width="400" height="400">
    </div>
  </div>
</template>

<script>
import vueEsign from 'vue-esign'
export default {
  data(){
    return {
      lineWidth: 2,
      lineColor: '#000000',
      resultImg: '',
      isCrop: false,

      imgSrc:'',
    }
  },
  components: {
    vueEsign,
  },
  methods:{
    // 清空画布
    handleReset () {
      this.$refs.esign.reset()
    },
    // 生成签名的base64图片
    handleGenerate () {
      this.$refs.esign.generate().then(res => {
        this.imgSrc = res;
        console.log(res,this.base64ImgtoFile(res))
      }).catch(err => {
        console.log('画布没有签字时会执行这里 Not Signned')
      })
    },
    // 附：base64转化成图片
    base64ImgtoFile(dataurl, fileName='file') {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1]);
      let n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${fileName}.${suffix}`, { type: mime });
    },
  },
}
</script>
